#include "pch.h"

using std::string;
using std::ifstream;
using std::ofstream;
using std::map;
using std::vector;

map<string, int> OpeningBookUtil::book;

bool OpeningBookUtil::load(const string & path) {
	book.clear();

	ifstream file(path);

	if (!file.is_open()) {
		return false;
	}

	int size;
	string state;
	int pos;

	//file >> size;
	while (!file.eof()) {
		file >> state;
		file >> pos;

		book[state] = pos;
	}

	file.close();

	return true;
}

bool OpeningBookUtil::save(const string & path) {
	ofstream file(path);

	if (!file.is_open()) {
		return false;
	}

	for (map<string, int>::iterator i = book.begin(); i != book.end(); i++) {
		file << (*i).first << " " << (*i).second << "\n";
	}

	file.close();

	return true;
}

bool OpeningBookUtil::append(const string & path) {
	ifstream file(path);

	if (!file.is_open()) {
		return false;
	}


	int size;
	string state;
	int pos;

	file >> size;
	while (!file.eof()) {
		file >> state;
		file >> pos;

		book[state] = pos;
	}

	file.close();

	return true;
}

int OpeningBookUtil::del(const string & state) {
	if (book.find(state) == book.end()) {
		return -1;
	}

	int temp = book[state];

	book.erase(state);

	return temp;
}


/*
	return: 1\ update, 2\ add
*/
int OpeningBookUtil::add_or_update(const string & state, int pos) {
	if (book.find(state) == book.end()) {
		book[state] = pos;
		return 2;
	}

	book[state] = pos;

	return 1;
}

void OpeningBookUtil::states(vector<string> & out) {
	out.clear();

	for (map<string, int>::iterator i = book.begin(); i != book.end(); i++) {
		out.push_back((*i).first);
	}
}

int OpeningBookUtil::get(const string & state) {
	if (book.find(state) == book.end()) {
		return -1;
	}

	return book[state];
}